package multithreading;


import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: 海琳琦
 * @Date: 2022/4/3 17:03
 * 解决线程同步问题----lock锁
 * 1、实例化reentrantlock 2、调用lock方法 3、调用unlock()方法
 * 说明：reentrantlock方法必须紧跟try，且在finally的第一行使用对象.unlock()解锁
 */
class Ticket2 implements Runnable{

    private int ticket = 10011;

    /**
     * fair：按先后顺序执行（公平）
     * 1、实例化reentrantlock
     */
    private ReentrantLock reentrantLock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            reentrantLock.lock();
            try {
                Thread.sleep(10);
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "售出票号： " + ticket);
                    ticket--;
                }else{
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally{
                reentrantLock.unlock();
            }
        }
    }
}

public class TicketDemo2 {

    public static void main(String[] args) {
        Ticket2 ticket = new Ticket2();
        Thread thread1 = new Thread(ticket);
        Thread thread2 = new Thread(ticket);
        Thread thread3 = new Thread(ticket);
        thread1.setName("窗口1");
        thread2.setName("窗口2");
        thread3.setName("窗口3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
